﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
//using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
//using System.Xml.Linq;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;


public partial class OrderPlacement : System.Web.UI.Page
{

    double monto;
    double psfmonto;
    int copiarorden;
    string stordernum = "";
    rUser ruser;
    DataSet ds = null;//fill products
    DataSet dst = null;//fill state
    DataSet dsc = null;// fill counties
    DataSet dsacc = null;//fill account
    string client ;
    string company ;
    string account ;
    string agent="";
    public long RNOrd = 0, PNOrd = 0;
    
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {

            Response.Redirect("../Default.aspx");
        }
        else
        {
            ruser = (rUser)Session["userid"];
            if (ruser != null)
            {
                RE_GenericBean permit = new RE_GenericBean();
                permit = Utility.getPermisobyRuser(ruser, 2);//pagina new order
                PNOrd = permit.int64C1;
                RNOrd = permit.int64C2;
            }
            if (Page.IsPostBack == false)
            {
                psfmonto = 0;
                fillproducts(ruser);
                fillstates();
                copiarorden = 1;
                fillclients();
                fillcompanies();

                fillaccounts();
                fillarea();
                fillsector();
                PConInfo1.Visible = false;
                PConInfo2.Visible = false;
                

            }
            else {
                string sstate = state.Text;
                string sopstate = cbOPState.Text;
                string scounty = county.Text;
                //fillstates();
                //fillcounties(sstate);
                state.Text = sstate;
                cbOPState.Text = sopstate;
                ruser = (rUser)Session["userid"];
               
                if (county.Items.Count > 0) {
                    for (int i = 0; i < county.Items.Count - 1;i++ ) {
                        if (county.Items[i].Text.Equals(scounty)) {
                            county.Items[i].Selected = true;
                        }
                    }
                }
            }

            restricted();
            permiso();

            if (Session[""] != null)
            {
                int paidclient = (int)Session["paidclient"];

                if (paidclient == 1)
                {
                    Session["paidclient"] = null;
                    p_hide_ModalPopupExtender.Hide();
                    Response.Redirect("WorkSpace.aspx");
                }
                if (paidclient == 2)
                {
                    Session["paidclient"] = null;
                    p_hide_ModalPopupExtender.Hide();
                    Response.Redirect("OrderPlacement.aspx");
                }
            }
        }
        cb_sector.Enabled = false;
        county.Enabled = false;
        PpsfPrice.Visible = false;
        PpsfPrice2.Visible = false;
        lnk_saveadd.Visible = false;
        if (!ruser.getPerfilId().Equals("1") ) {
            PpsfPrice.Visible = true;
            PpsfPrice2.Visible = true;
            lnk_saveadd.Visible = true;
        }
        P_viewcart.Visible = false;
        cbclient.AutoPostBack = false;
        if (ruser.getPerfilId().Equals("1")) {
            if ((PNOrd & 2097152) == 2097152)
            {
                P_viewcart.Visible = true;
                cbclient.AutoPostBack = true;
            }
        }
    }

    private void fillaccounts()
    {
        try {
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml=service.getAccounts();
            

            if (!rxml.Equals("") || rxml != null)
            {
                dsacc = Utility.getAccounts(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "Select One"; listitem0.Value = "";
                cbaccount.Items.Add(listitem0);

                ruser = (rUser)Session["userid"];
                for (int ii = 0; ii <= (dsacc.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text =   dsacc.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsacc.Tables[0].Rows[ii][0].ToString();
                    cbaccount.Items.Add(listitem);

                    if (ruser.getAlias().Equals(dsacc.Tables[0].Rows[ii][2].ToString()))
                    {
                        cbaccount.SelectedValue = listitem.Value;
                    }
                }
            }
            Session["Accounts"] = dsacc;

        
        } 
        catch (Exception ee){
            Utility.writeError(ee.Message);
        
        }
    }

    private void fillcompanies()
    {
        try
        {
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.getCompanies();


            if (!rxml.Equals("") || rxml != null)
            {
                DataSet dsclient = Utility.getCompanies(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "Select One"; listitem0.Value = "";
                cbcompany.Items.Add(listitem0);


                for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsclient.Tables[0].Rows[ii][1].ToString();
                    listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                    cbcompany.Items.Add(listitem);
                    

                }
                if (ruser.getPerfilId().ToUpper().Equals("1"))
                {
                    if (!ruser.getUsuarioId().Equals("PACIFICSTAR") && !ruser.getUsuarioId().Equals("FIVESTAR") && !ruser.getUsuarioId().Equals("RICOPALMA") && !ruser.getUsuarioId().Equals("JONASRANGEL") && !ruser.getUsuarioId().Equals("OGOLANSKY"))
                    {
                        cbcompany.SelectedValue = "1";
                        //uitest.Text = cbcompany.SelectedValue.ToString();
                    }
                }
            }

        }catch(Exception ee){
            Utility.writeError(ee.Message+ ee.StackTrace);
            
        }
    }

    private void fillclients()
    {
        try
        {
            string rxml = null;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            rxml = service.UsuariosPorPerfil(1);

            if (!rxml.Equals("") || rxml != null)
            {
                DataSet dsclient = Utility.getUsuariosporPerfil(rxml);
                ListItem listitem0 = new ListItem();
                listitem0.Text = "Select One"; listitem0.Value = "";
                cbclient.Items.Add(listitem0);

                ruser = (rUser)Session["userid"];
                for (int ii = 0; ii <= (dsclient.Tables[0].Rows.Count - 1); ii++)
                {
                    ListItem listitem = new ListItem();
                    listitem.Text = dsclient.Tables[0].Rows[ii][2].ToString() + " " + dsclient.Tables[0].Rows[ii][1].ToString(); 
                    listitem.Value = dsclient.Tables[0].Rows[ii][0].ToString();
                    cbclient.Items.Add(listitem);
                   
                    if (ruser.getUsuarioId().Equals(listitem.Value)){
                        cbclient.SelectedValue= listitem.Value;
                        
                    }

                }
            }

        }catch(Exception ee){
            Utility.writeError(ee.Message);
        }
    }

    private void fillproducts(rUser user)
    {
        
         ds = DB.GetProducts();
        if (user.getPerfilId().ToUpper().Equals("1")){
       
            DataSet dsuser = DB.GetProductsbyUser(user.getUsuarioId());
        if (ds != null && dsuser!= null)
        {
            ListItem li = new ListItem();
            li.Text = "Select One";
            li.Value = "0";
            jobtype.Items.Add(li);
            for (int j = 0; j <= (dsuser.Tables[0].Rows.Count - 1); j++)
            {

                for (int i = 0; i <= (ds.Tables[0].Rows.Count - 1); i++)
                {
                    if (!ds.Tables[0].Rows[i][0].ToString().ToUpper().Equals("0") && dsuser.Tables[0].Rows[j][0].ToString().Equals(ds.Tables[0].Rows[i][0].ToString()))
                    {
                        li = new ListItem();
                        li.Text = ds.Tables[0].Rows[i]["name"].ToString();
                        li.Value = ds.Tables[0].Rows[i][0].ToString();
                        jobtype.Items.Add(li);
                    }

                }
            }
        }
        }else{
            ListItem li = new ListItem();
            li.Text = "Select One";
            li.Value = "0";
            jobtype.Items.Add(li);
            for (int i = 0; i <= (ds.Tables[0].Rows.Count - 1); i++)
            {
                if (!ds.Tables[0].Rows[i][0].ToString().ToUpper().Equals("0") )
                {
                    li = new ListItem();
                    li.Text = ds.Tables[0].Rows[i]["name"].ToString();
                    li.Value = ds.Tables[0].Rows[i][0].ToString();
                    jobtype.Items.Add(li);
                }

            }
        
        }
       
    }

    private void fillstates() {

       
            state.Items.Clear();
            cbOPState.Items.Clear();
            dst = DB.GetStates();
            if (dst != null)
            {
                state.Items.Add("Select One");
                cbOPState.Items.Add("Select One");
                for (int i = 0; i <= (dst.Tables[0].Rows.Count - 1); i++)
                {
                    if (dst.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
                    {
                        ListItem Li = new ListItem();
                        Li.Value = dst.Tables[0].Rows[i]["state_id"].ToString();
                        Li.Text = dst.Tables[0].Rows[i]["name"].ToString().ToUpper();
                        state.Items.Add(Li);
                        cbOPState.Items.Add(Li);


                    }
                }
            }
    
    }

    private void fillcounties(string state)
    {
        if (!state.ToUpper().ToString().Equals("SELECT ONE"))
        {
            string nameItem;
            county.Items.Clear();
            //county.Enabled = true;
            dsc = DB.GetCounties(state);
            county.Items.Add("Select One");
            if (dsc != null)
            {
                
                if (dsc.Tables[0].Rows.Count > 0)
                {
                    
                    for (int i = 0; i <= (dsc.Tables[0].Rows.Count - 1); i++)
                    {
                       
                            ListItem list = new ListItem();
                             //nameItem = dsc.Tables[0].Rows[i]["name"].ToString();
                            list.Value = dsc.Tables[0].Rows[i][0].ToString();
                            list.Text = dsc.Tables[0].Rows[i]["name"].ToString();
                             county.Items.Add(list);
                                                
                       

                    }
                }
                else
                {
                    county.Text = "Select One";
                    county.Enabled = false;
                }
            }
        }
        else {
            county.Text = "Select One";
            county.Enabled = false;
        }
       
    }

    private void fillcountiesop(string state)
    {

        string nameItem;
        dsc = DB.GetCounties(state);
        cbOPState.Enabled = true;
        if (dsc != null)
        {

            if (dsc.Tables[0].Rows.Count > 0)
            {
                cbOPState.Items.Add("Select One");
                for (int i = 0; i <= (dsc.Tables[0].Rows.Count - 1); i++)
                {
                    nameItem = dsc.Tables[0].Rows[i]["name"].ToString();
                    cbOPState.Items.Add(nameItem);
                    string enable = dsc.Tables[0].Rows[i]["enable"].ToString();
                    if (dsc.Tables[0].Rows[i]["enable"].ToString().Equals("0"))
                    {

                        cbOPState.Items[county.Items.Count - 1].Attributes.Add("style", "color:gray;");
                        cbOPState.Items[county.Items.Count - 1].Attributes.Add("disabled", "true");
                        cbOPState.Items[county.Items.Count - 1].Value = "-1";

                    }




                }
            }
            else
            {
                county.Enabled = false;
            }
        }

    }
    
    protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
    {

       
        DataSet dsuser = DB.GetProductsbyUser(cbclient.SelectedValue);
        if (dsuser != null) {
            for (int j = 0; j <= (dsuser.Tables[0].Rows.Count - 1); j++)
            {
                if (jobtype.SelectedValue.Equals(dsuser.Tables[0].Rows[j][0].ToString())) {
                    setMonto();
                    //amount.Text = Utility.formatNumber(dsuser.Tables[0].Rows[j][1].ToString());
                    
                    PaypalButt(ruser.getUsuarioId(), monto.ToString(), new RE_GenericBean());
                }
            }

        }
        /*double client_fee;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        string fee3= service.getClientProductFee(cbclient.SelectedValue, jobtype.SelectedValue);
        if (fee3.Equals("")) { fee3 = DB.findProductFee(jobtype.SelectedValue).ToString(); }
         monto = double.Parse(fee3);
         client_fee = 0.0;
         if ( !fee3.Equals("")){
             client_fee = double.Parse(fee3);
         }
         if (exp.Checked == true)
         {

             monto = monto + 3.00;

         }
         else {
             monto =client_fee;
         }
         amount.Text = Utility.formatNumber(monto);
             
        */

            if (DB.hasOptional(jobtype.SelectedValue) == 1)
            {

                addoptional();
            }
            else {
                removeoptional();
            
            }
            string type = DB.getProductType(jobtype.Text);
            if (type.ToUpper().Equals("INT") || type.ToUpper().Equals("INTREP"))
            {
                PConInfo1.Visible = true;
                PConInfo2.Visible = true;
            }
            else {
                PConInfo1.Visible = false;
                PConInfo2.Visible = false;
            
            }
            if (cbclient.SelectedValue.Equals("PACIFICSTAR") && cbcompany.SelectedItem.ToString().ToUpper().Equals("EVALONLINE")) {

                cb_source.Visible = true;
                cb_source.ForeColor = System.Drawing.Color.Blue;
            }

            
            
    }

    private void PaypalButt(string usuid, string ammount, RE_GenericBean rinfo)
    {
        /*string butadd = "<form  action=\"https://www.sandbox.paypal.com/cgi-bin/webscr\" method=\"post\"><input type=\"hidden\" name=\"cmd\" value=\"_cart\"/>";
        butadd+= "<input type=\"hidden\" name=\"business\" value=\"UFFECEVK5TH58\"/> <input type=\"hidden\" name=\"add\" value=\"1\"/> <input type='hidden' name='lc' value='en'/>";
        butadd+= "<input type=\"hidden\" name=\"amount\" value=\""+ammount+"\" /><input type=\"hidden\" name=\"currency_code\" value=\"USD\"/><input type=\"hidden\" name=\"item_name\" value=\""+jobtype.SelectedItem.ToString()+"\"/>";
        butadd+= " <input type=\"hidden\" name=\"item_number\" value=\""+jobtype.SelectedValue.ToString()+"\">";
        butadd+= "<input type=\"image\" src=\"https://www.paypal.com/en_US/i/btn/x-click-but10.gif\"  name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"./></form>";
         */

        string butadd = "<form   action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\"><input type=\"hidden\" name=\"cmd\" value=\"_cart\"/>";
        butadd += "<input type=\"hidden\" name=\"business\" value=\"UC5TPPY3Z8XBN\"/><input type=\"hidden\" name=\"display\" value=\"0\"/>  <input type=\"hidden\" name=\"add\" value=\"1\"/><input type=\"hidden\" name=\"lc\" value=\"US\"/>";
        butadd += "<input type=\"hidden\" name=\"amount\" value=\"" + ammount + "\" /><input type=\"hidden\" name=\"currency_code\" value=\"USD\"/> ";
        butadd += "<input type=\"hidden\" name=\"item_name\" value=\"" + ruser.getNombre() +" "+ruser.getApellido()+ "\" />";
        butadd += "<input type=\"hidden\" name=\"item_number\" value=\"" + rinfo.strC2 +"\"/>";
        butadd += "<input type=\"image\" src=\"https://www.paypal.com/en_US/i/btn/x-click-but10.gif\"  name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"./></form>";

        /*
                string butadd = "<form   action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\"><input type=\"hidden\" name=\"cmd\" value=\"_cart\"/>";
                butadd += "<input type=\"hidden\" name=\"business\" value=\"UC5TPPY3Z8XBN\"/><input type=\"hidden\" name=\"display\" value=\"0\"/>  <input type=\"hidden\" name=\"add\" value=\"1\"/><input type=\"hidden\" name=\"lc\" value=\"US\"/>";
                butadd += "<input type=\"hidden\" name=\"amount\" value=\"" + ammount + "\" /><input type=\"hidden\" name=\"currency_code\" value=\"USD\"/> ";
                butadd += "<input type=\"hidden\" name=\"item_name\" value=\"Client: " + ruser.getNombre() + " " + ruser.getApellido() + ". \n Product Type:" + jobtype.SelectedItem.ToString() + ".\n Address: " + rinfo.strC3 + " " + rinfo.strC4 + "\" />";
               butadd += "<input type=\"hidden\" name=\"item_number\" value=\"" + rinfo.strC2 + "\"/>";
                butadd += "<input type=\"image\" src=\"https://www.paypal.com/en_US/i/btn/x-click-but10.gif\"  name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"./></form>";
                */

        lbuy.Text= butadd;

        /* string butchk= "<form   action=\"https://www.sandbox.paypal.com/cgi-bin/webscr\" method=\"post\">";
         butchk+= "<input type=\"hidden\" name=\"business\" value=\"UC5TPPY3Z8XBN\"/>";
         butchk+= "<input type=\"hidden\" name=\"cmd\" value=\"_cart\"/>";
         butchk+= "<input type=\"hidden\" name=\"display\" value=\"1\"/>";
         butchk+= "<input type=\"image\" src=\"https://www.paypalobjects.com/en_US/i/btn/view_cart_02.gif\"  name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"./>";
         butchk+= "<input type=\"hidden\" name=\"lc\" value=\"en\"/></form>  ";
         */

        string butchk = "<form   action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\">";
        butchk += "<input type=\"hidden\" name=\"business\" value=\"UC5TPPY3Z8XBN\"/>";
        butchk += "<input type=\"hidden\" name=\"cmd\" value=\"_cart\"/>";
        butchk += "<input type=\"hidden\" name=\"display\" value=\"1\"/>";
        butadd += "<input type=\"hidden\" name=\"invoice\" value=\"" + rinfo.strC2 + "\"/>";
        butchk += "<input type=\"hidden\" name=\"image_url\" value=\"http://www.bpophotos.com/img/VickoLogo2.png\">";
        butchk += "<input type=\"image\" src=\"https://www.paypalobjects.com/en_US/i/btn/view_cart_02.gif\"  name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"./>";
        butchk += "<input type=\"hidden\" name=\"lc\" value=\"en\"/></form>  ";

        /* string butchk = "<form   action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\">";
         butchk += "<input type=\"hidden\" name=\"business\" value=\"UC5TPPY3Z8XBN\"/>";
         butchk += "<input type=\"hidden\" name=\"cmd\" value=\"_cart\"/>";
         butchk += "<input type=\"hidden\" name=\"display\" value=\"1\"/>";
          butadd += "<input type=\"hidden\" name=\"invoice\" value=\"" + rinfo.strC2 + "\"/>";
         butchk += "<input type=\"hidden\" name=\"image_url\" value=\"http://www.bpophotos.com/img/VickoLogo2.png\">";
         butchk += "<input type=\"image\" src=\"https://www.paypalobjects.com/en_US/i/btn/view_cart_02.gif\"  name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"./>";
         butchk += "<input type=\"hidden\" name=\"lc\" value=\"en\"/></form>  ";
         */
        // ladd.Text= butchk;

    }

    



       
        
    

    private int guardarbd()
    {

        SqlTransaction transaction;
        SqlConnection conn = null;
        SqlCommand insert;
        conn = DB.OpenConnection();
        transaction = conn.BeginTransaction();
      
       
        
        
        ruser = (rUser)Session["userid"];
        int result = 0;
        try
        {
             
            insert = new SqlCommand();
           
            insert.Connection = conn;
            insert.CommandType = CommandType.Text;
            insert.Transaction = transaction;
           
            
            string hour = DateTime.Now.ToShortTimeString();
           
             int nextOrderId;
           
            nextOrderId = DB.getNextOrderId();
            if (nextOrderId == 1)
            {
                nextOrderId = 10000;
            }
            if (CheckBox1.Checked)
            {

                stordernum = nextOrderId.ToString();
            }
            else {
                if (!ordernum.Text.Equals(""))
                {
                    stordernum = ordernum.Text;
                }
                else {
                    stordernum = nextOrderId.ToString();
                }
            }
           
            // DateTime fecha = DateTime.Parse(Duedate.SelectedDate.ToString()); 
           
            int produc_id = int.Parse(jobtype.SelectedValue);
            int state_id = int.Parse(state.SelectedValue);
            int county_id = int.Parse(county.SelectedValue);
            setaccount();
            setcliente();
            setcompany();
            setMonto();
            setpsfMonto();
           
           
            string q = "insert into [ORDER](order_id,product_id, client_id, status_id, duedate, duetime, fee, comments, stnum, stadd, stcity, state, zip, county, ";
            if (cb_source.Checked)
            {
                q = q + "  ord_commisionname, ";
            }
            if (psfmonto == 0.00)
            {
                q = q + ("opstnum, opstadd, opcity, opstate, opzip, ord_area,  ord_sector,ord_date, ord_time,ordernum, account, company, contactinfo, ord_agent, ord_drvcomment, unit) ");
            }
            else
            {
                q = q + ("opstnum, opstadd, opcity, opstate, opzip, ord_area, ord_sector, ord_date, ord_time,ordernum, account, company, contactinfo, psfprice, ord_agent, ord_agent_done, ord_agent_date, ord_agent_time, ord_drvcomment, unit) ");
            }
           
            //orderid, vendorid, productid, clientid, status
            q = q + "values(  @nextOrderId,  @produc_id ,  @client , 1, ";
           // q = q + "values(" + nextOrderId + "," + produc_id + " , '"+client+"' , 1, '";
            //calcular monto
            //duedate, duetime,monto, coments
            //q= q+ fecha.ToShortDateString()+"', \'"+duetime.Text+"' , "+monto+", '"+comments.Text+"' ,";
            if (!P_duedate2.Visible==false) {
                q = q + "@Duedate, @duetime, @getmonto ,  @comments  ,";
            } 
            else {
                q = q + "DATEADD(day,+2,GETDATE()), @duetime, @getmonto ,  @comments  ,";
            }
            //q = q + "@Duedate, @duetime, @getmonto ,  @comments  ,";
            //q = q + Duedate.Text + "', '" + Utility.HoraAMPMtoFormato24horas(duetimehour.Text, duetimeampm.Text) + "' , " + getmonto() + ", '" + comments.Text + "' ,";
            //stnum,stadd,city,state
            q = q + "  @stnum, @stadd , @city , @state_id  ,";
           // q = q + " '" + stnum.Text.ToUpper() + "', '" + stadd.Text.ToUpper() + "' , '" + city.Text.ToUpper() + "' , " + state_id + " ,";
            //zip,country,opstnum
            q = q + " @zip , @county_id  ";
             if (cb_source.Checked)
            {
                q = q + ", @commisionname";
                insert.Parameters.Add("@commisionname", SqlDbType.VarChar).Value = "Stephanie Barlow";
            }
            
            //q = q + "'" + zip.Text + "' , " + county_id+ "  , '" + opstnumber.Text.ToUpper() + "' ,";
            // opstad, opcity, opstate, opzip
            q = q + ",  @opstnumber , @opstadd  , @opcity ,@cbOPState, @opzip, @area,@sector";
            //q = q + " '" + opstadd.Text.ToUpper() + "' , '" + opcity.Text.ToUpper() + "' , '" + cbOPState.Text.ToUpper() + "' , '" + opzip.Text;
           
            if (psfmonto==0.00){
                q = q + ", getdate() ,@hour , @stordernum ,@account , @company , @ContactInformation, @agent, @comments , @unit )";
               // q= q +"','"+ord_date+"','"+ hour+ "',"+stordernum+","+account+", "+ company+", '"+ContactInformation.Text+"' )";
            }else{
                q = q + ", getdate() , @hour ,@stordernum ,@account , @company , @ContactInformation ,@psfmonto, @agent, 'YES' ,getdate(), @agentime, @comments, @unit)";
                insert.Parameters.Add("@psfmonto", SqlDbType.Real).Value = psfmonto;
                //q = q + "','" + ord_date + "','" + hour + "'," + stordernum + "," + account + ", " + company + ", '" + ContactInformation.Text + "'," + psfmonto + " )";
            }
           
             insert.CommandText = q;
             insert.Parameters.Add("@nextOrderId", SqlDbType.Int).Value = nextOrderId;
             insert.Parameters.Add("@produc_id", SqlDbType.Int).Value = produc_id;
             insert.Parameters.Add("@client", SqlDbType.VarChar).Value = client;
             if (!P_duedate2.Visible == false)
             {
                insert.Parameters.Add("@Duedate", SqlDbType.Date).Value = Duedate.Text;
            
            }

            // insert.Parameters.Add("@Duedate", SqlDbType.Date).Value = Duedate.Text;
             insert.Parameters.Add("@duetime", SqlDbType.VarChar).Value = Utility.HoraAMPMtoFormato24horas(duetimehour.Text, duetimeampm.Text);
             insert.Parameters.Add("@getmonto", SqlDbType.Real).Value = getmonto();
             insert.Parameters.Add("@comments", SqlDbType.VarChar).Value= comments.Text.ToUpper();
             insert.Parameters.Add("@stnum", SqlDbType.VarChar).Value= stnum.Text.ToUpper();
             insert.Parameters.Add("@stadd", SqlDbType.VarChar).Value = stadd.Text.ToUpper();
             insert.Parameters.Add("@city", SqlDbType.VarChar).Value = cb_city.SelectedItem.ToString().ToUpper();
             insert.Parameters.Add("@state_id", SqlDbType.Int).Value = state_id;
             insert.Parameters.Add("@zip", SqlDbType.VarChar).Value = zip.Text;
             insert.Parameters.Add("@county_id", SqlDbType.Int).Value = county_id;
             insert.Parameters.Add("@opstnumber", SqlDbType.VarChar).Value = opstnumber.Text;
             insert.Parameters.Add("@opstadd", SqlDbType.VarChar).Value = opstadd.Text.ToUpper();
             insert.Parameters.Add("@opcity", SqlDbType.VarChar).Value = opcity.Text;
             insert.Parameters.Add("@cbOPState", SqlDbType.VarChar).Value = cbOPState.Text.ToUpper();
             insert.Parameters.Add("@opzip", SqlDbType.VarChar).Value = opcity.Text.ToUpper();
             insert.Parameters.Add("@area", SqlDbType.VarChar).Value = cb_area.SelectedValue.ToString().ToUpper();
             insert.Parameters.Add("@sector", SqlDbType.VarChar).Value = cb_sector.SelectedValue.ToString().ToUpper();
             
             insert.Parameters.Add("@hour", SqlDbType.VarChar).Value = hour;
             insert.Parameters.Add("@stordernum", SqlDbType.VarChar).Value = stordernum;
             insert.Parameters.Add("@account", SqlDbType.Int).Value = account;
             insert.Parameters.Add("@company", SqlDbType.Int).Value = company;
             insert.Parameters.Add("@ContactInformation", SqlDbType.VarChar).Value = ContactInformation.Text.ToUpper();
             insert.Parameters.Add("@agent", SqlDbType.VarChar).Value = agent;
             insert.Parameters.Add("@agentime", SqlDbType.VarChar).Value = hour;
             insert.Parameters.Add("@unit", SqlDbType.VarChar).Value = tb_unit.Text;
        


             insert.ExecuteNonQuery();
               
          
            string now = DateTime.Now.ToString();

            q = "INSERT INTO comparables (order_id)  VALUES  (" + nextOrderId + ")";
            insert.CommandText = q;
            insert.ExecuteNonQuery();

            q = "INSERT INTO QCSUB (order_id)  VALUES  (" + nextOrderId + ")";
            insert.CommandText = q;
            insert.ExecuteNonQuery();

            transaction.Commit();

            result = nextOrderId;

        }catch(Exception e){
            transaction.Rollback();
            lerror.Text = "Error on page. Please save again.";
            Utility.writeError(e.Message + ", " + e.StackTrace + " %% account " + account);
            result = 0;

        
        }
        return result;

       
    }

    private void setpsfMonto()
    {
        
        try {
            psfmonto = Convert.ToDouble(txtpsfprice.Text);
        }catch(Exception e){
            psfmonto = 0.00;
        }
    }

    private void setaccount()
    {
        account = "";
       
            if (!cbaccount.Text.Equals("Select One"))
            {
                account = cbaccount.SelectedValue;
            }

            Utility.writeError("Account Orderplacement"+account);
    }

    private void setcompany()
    {
        company = "";
          
             if (!cbcompany.Text.Equals("Select One")){
              company = cbcompany.SelectedValue;
            
        }
    }

    private void setcliente()
    {
        if (ruser.getPerfilId().ToUpper().Equals("1"))
        {
            client = ruser.getUsuarioId();
        }
        else {
            client = cbclient.Text;
        }

        dsacc= (DataSet)Session["Accounts"];
        if (dsacc == null)
        {
            dsacc = cargaraccounts();
        }
        PpsfPrice.Visible = false;
        if (client.Trim().ToUpper().Equals("PACIFICSTAR")){
            PpsfPrice.Visible = true;

            if (dsacc!=null){
                for (int ii = 0; ii <= (dsacc.Tables[0].Rows.Count - 1); ii++)
                {
                    string name = dsacc.Tables[0].Rows[ii][0].ToString().ToUpper();
                    if (account.ToUpper().Equals(name)) {
                        agent = dsacc.Tables[0].Rows[ii][2].ToString().ToUpper();
                        
                    }

                }
            }

            
        
        }else if(client.Trim().ToUpper().Equals("FIVESTAR")){
            agent = "SR";
        }
        else if (client.Trim().ToUpper().Equals("RICOPALMA")) 
        {
            agent= "VP";
        }else if (client.Trim().ToUpper().Equals("OGOLANSKY"))
         {
             agent = "PJ";
         }
        else if (client.Trim().ToUpper().Equals("JONASRANGEL"))
        {
            agent = "VIO";
        }
        else  {
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            string datos = service.getDatosUsuario(client);
            rUser rclient = Utility.getRUser(datos);
            if (rclient!= null) agent = rclient.getAlias();
        }
    

       
    }

    private double getmonto()
    {

        if (!txtpsfprice.Text.Equals("")){

            try
            {
               psfmonto = double.Parse(txtpsfprice.Text);
            }catch(Exception  e){
                //setMonto();
               
            }
        }
        else{
                setMonto();
        }
        return monto;
    }

    protected void setMonto() {

        if (cbclient.SelectedIndex != 0 && jobtype.SelectedIndex != 0)
        {
            ruser = (rUser)Session["userid"];
            double client_fee;
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            string fee3 = service.getClientProductFee(cbclient.SelectedValue, jobtype.SelectedValue);
            double fee4 = DB.getCityExtraFee(cb_city.SelectedValue);
            if (fee3.Equals("")) { fee3 = DB.findProductFee(jobtype.SelectedValue).ToString(); }
            monto = double.Parse(fee3);
            client_fee = 0.0;
            monto = monto + fee4;
            int dia = Utility.ValidateDate(Duedate.Text);
            int manana = Utility.isTomorrow(Duedate.Text);
            if (!fee3.Equals(""))
            {
                client_fee = double.Parse(fee3)+ fee4;
            }

            //agrego expedite si es para manna y son mas de las 8pm
            string hora=DateTime.Now.Hour.ToString();
            if ((manana == 1 && ruser != null && ruser.getPerfilId().Equals("1"))&& DateTime.Now.Hour>19)
            {

                monto = monto + 3.50;

            }
            else
            {
                //agrego expedite si es para hoy
                if (exp.Checked == true || (dia == 2 && ruser != null && ruser.getPerfilId().Equals("1")))
                {
                    monto = monto + 3.50;
                }
                else
                {
                    monto = client_fee;
                }
            }
            //agrego extracharge si esta en otros condados mas caros
            int countyid=0; int productid=0;
            try { countyid = int.Parse(county.SelectedValue); productid = int.Parse(jobtype.SelectedValue); }
            catch (Exception ex) { }
            RE_GenericBean extra = DB.getExtraFeebyCounty(countyid,productid);
            if (extra.intC1 == 1)
            {
                monto = monto + extra.doubleC1;
            }

           

            amount.Text = Utility.formatNumber(monto);

        }
    }
   
    //guardarbd
    
    private int validarCombo()
    {
        int result=1;
        if (state.SelectedValue.ToUpper().Equals("SELECT ONE"))
        {
            valstate.Text = "Select State";
            result = result * 0;
        }
        else {  valstate.Text = "";      }
        if (jobtype.SelectedValue.ToUpper().Equals("SELECT ONE"))
        {
            valproduct.Text = "Select Product";
            result = result * 0;
        }
        else { valproduct.Text = "";  }
        if (county.SelectedValue.ToUpper().Equals("Select One"))
        {
            valcounty.Text = "Select County";
            result = result * 0;
        }  else { valcounty.Text = ""; }

        if (duetimehour.SelectedValue.ToUpper().Equals("Select One"))
        {
            valduetime.Text = "Select Due Hour";
            result = result * 0;
        }
        else { valduetime.Text = ""; }
        if (duetimeampm.SelectedValue.ToUpper().Equals("Select One"))
        {
            valam.Text = "Select AM/PM";
            result = result * 0;
        }
        else { valam.Text = ""; }
    
      
        return result;
    }

    private void copiaropt()
    {
        if (opstnumber.Text.Equals("")) {
            opstnumber.Text = stnum.Text;
                   
        }
        if (opstadd.Text.Equals(""))
        {
            opstadd.Text = stadd.Text;

        }
        if (opcity.Text.Equals(""))
        {
            opcity.Text = cb_city.SelectedItem.ToString();

        }
        if (cbOPState.SelectedValue.Equals("Select One") )
        {
            cbOPState.Text = state.SelectedValue;

        }
        if (opzip.Text.Equals(""))
        {
            opzip.Text = zip.Text;

        }
    }
    protected void exp_CheckedChanged(object sender, System.EventArgs e)
    {
       /* double client_fee = product.findClientFee(jobtype.SelectedValue);
        monto = client_fee;
        if (exp.Checked == true) { monto = monto + 3.00; } 
        
        if (exp.Checked == false)
        {
            monto = client_fee;
           
        }
        amount.Text = Utility.formatNumber(monto);
        * */
        setMonto();
           
    
    }

    protected void addoptional() {
        PanelPickup.Visible = true;
        PanelPickup.Enabled = true;
    
    }

    protected void removeoptional()
    {
        PanelPickup.Visible = false;

    }

    protected void fillcounties_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        
        setMonto();
        

    }
    protected void fillcountiesopt_SelectedIndexChanged(object sender, EventArgs e)
    {

        fillcountiesop(state.SelectedItem.ToString());
    }
    protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
    {

        if (CheckBox1.Checked)
        {
            ordernum.Enabled = false;
            copiarorden = 0;
        }
        else {
            ordernum.Enabled = true; copiarorden = 1;
        }
               
    }
    protected void ordernum_TextChanged(object sender, EventArgs e)
    {
        
    }

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {

    }

    public void restricted()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        PClient1.Visible = false;
        PClient2.Visible = false;
       
        if (user != null)
        {
            //permiso = long.Parse(user.getRestricted().ToString());
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 2);
            permiso = permi.int64C2;
        }
        if ((permiso & 1) == 1) { Response.Redirect(Request.UrlReferrer.ToString()); }
        if (((permiso & 4) == 4))// view client
        {
            PClient1.Visible = true;
            PClient2.Visible = true;
            cbclient.Enabled = true;
        }
        //Duedate
        if (((permiso & 8) == 8)){  P_duedate1.Visible = false; P_duedate2.Visible = false;}
        //Duetime       
        if (((permiso & 16) == 16)) { P_duetime1.Visible = false; P_duetime2.Visible = false; }
        //Company
        if (((permiso & 32) == 32)) {  P_company1.Visible = false; P_company2.Visible = false;  }
        //Account
        if (((permiso & 64) == 64)) { P_acc1.Visible = false; P_acc2.Visible = false; }
        //Job type
        if (((permiso & 128) == 128)) { P_job1.Visible = false; P_job2.Visible = false; }
        //Custom Order#
        if (((permiso & 256) == 256)) { ordernum.Visible = false; CheckBox1.Visible = true; CheckBox1.Checked = true; CheckBox1.Enabled = false; }
        ///street#
        if (((permiso & 512) == 512)){ P_st1.Visible = false; P_st1.Visible = false; }
            
         //Street Address
         if (((permiso & 1024) == 1024)){P_stad1.Visible = false; P_stad2.Visible = false;}
         //Zip
         if (((permiso & 2048) == 2048)) { P_zip1.Visible = false; P_zip2.Visible = false; }
        //City
        if (((permiso & 4096) == 4096)) {P_city1.Visible = false; UpdatePanel1.Visible = false; }
        
         //State   
        if (((permiso & 8192) == 8192)){P_state1.Visible = false; UpdatePanel2.Visible = false;}
        
        //County
        if (((permiso & 16384) == 16384)){ P_conty1.Visible = false; UpdatePanel3.Visible = false;}
        //Area
        if (((permiso & 32768) == 32768)) { P_area1.Visible = false; UpdatePanel4.Visible = false;}
        
           
        //Sector
        if (((permiso & 65536) == 65536)){P_sector1.Visible = false; P_sector2.Visible = false;}
        
         //Comments   
        if (((permiso & 131072) == 131072)) {P_comments1.Visible = false; P_comments2.Visible = false; }
       //Contact Info
           if (((permiso & 262144) == 262144))  { PConInfo1.Visible = false; PConInfo2.Visible = false;    }

                
        
       
       
        
       
      
    }

    public void permiso()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        PClient1.Visible = false;
        PClient2.Visible = false;
       
        if (user != null)
        {
           // permiso = long.Parse(user.getPermisoUser().ToString());
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 2);
            permiso = permi.int64C1;
        }
        
        if (((permiso & 4) == 4))// view client
        {
            PClient1.Visible = true;
            PClient2.Visible = true;
            cbclient.Enabled = true;
        }
        if ((PNOrd & 524288) != 524288) { lnk_save.Enabled = false; }
        if ((PNOrd & 1048576) != 1048576) { lnk_saveadd.Enabled = false; }
        //Duedate
        if (((permiso & 8) != 8)) { P_duedate1.Enabled = false; P_duedate2.Enabled = false; }
        //Duetime       
        if (((permiso & 16) != 16)) { P_duetime1.Visible = false; P_duetime2.Enabled = false; }
        //Company
        if (((permiso & 32) != 32)) { P_company1.Enabled = false; P_company2.Enabled = false; }
        //Account
        if (((permiso & 64) != 64)) { P_acc1.Enabled = false; P_acc2.Enabled = false; }
        //Job type
        if (((permiso & 128) != 128)) { P_job1.Enabled = false; P_job2.Enabled = false; }
        //Custom Order#
        if (((permiso & 256) != 256)) { P_order1.Enabled = false; P_order2.Enabled = false; }
        ///street#
        if (((permiso & 512) != 512)) { P_st1.Enabled = false; P_st1.Enabled = false; }

        //Street Address
        if (((permiso & 1024) != 1024)) { P_stad1.Enabled = false; P_stad2.Enabled = false; }
        //Zip
        if (((permiso & 2048) != 2048)) { P_zip1.Enabled = false; P_zip2.Enabled = false; }
        //City
        if (((permiso & 4096) != 4096)) { P_city1.Enabled = false; cb_city.Enabled = false; }

        //State   
        if (((permiso & 8192) != 8192)) { P_state1.Enabled = false;  }

        //County
        if (((permiso & 16384) != 16384)) { P_conty1.Enabled = false;  }
        //Area
        if (((permiso & 32768) != 32768)) { P_area1.Enabled = false;  }


        //Sector
        if (((permiso & 65536) != 65536)) { P_sector1.Enabled = false; P_sector2.Enabled = false; }

        //Comments   
        if (((permiso & 131072) != 131072)) { P_comments1.Enabled = false; P_comments2.Enabled = false; }
        //Contact Info
        if (((permiso & 262144) != 262144)) { PConInfo1.Enabled = false; PConInfo2.Enabled = false; }

        if ((permiso & 1) != 1) { lnk_save.Enabled = false; lnk_saveadd.Enabled = false; }
    }
    
    protected void fillarea() {
        cb_area.Items.Clear();
        
        DataSet ds = DB.getAreas();
        if (ds != null)
        {
            cb_area.Items.Add("Select One");
            for (int i = 0; i <= (ds.Tables[0].Rows.Count - 1); i++)
            {
                if (ds.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
                {
                    ListItem Li = new ListItem();
                    Li.Value = ds.Tables[0].Rows[i]["area_id"].ToString();
                    Li.Text = ds.Tables[0].Rows[i]["name"].ToString().ToUpper();
                    cb_area.Items.Add(Li);
                    


                }
            }
        }
    }
    protected void fillsector()
    {
        cb_sector.Items.Clear();

        DataSet ds = DB.getSectors();
        if (ds != null)
        {
            cb_sector.Items.Add("Select One");
            for (int i = 0; i <= (ds.Tables[0].Rows.Count - 1); i++)
            {
                if (ds.Tables[0].Rows[i]["enable"].ToString().Equals("1"))
                {
                    ListItem Li = new ListItem();
                    Li.Value = ds.Tables[0].Rows[i]["sector_id"].ToString();
                    Li.Text = ds.Tables[0].Rows[i]["name"].ToString().ToUpper();
                    cb_sector.Items.Add(Li);



                }
            }
        }
    }
    protected void zip_TextChanged(object sender, EventArgs e)
    {
        lzip.Visible = false; lb_coverage.Visible = false;
        if (zip.Text != "" && zip.Text.Length > 4)
        {
            DataSet ds;

            ds = DB.getDatosbyZip(zip.Text);
            int res = DB.comprobarZipCobertura(zip.Text);


            if (ds != null && ds.Tables[0].Rows.Count != 0 && res==1)
            {   //recorro el ds para poner nombres
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    state.SelectedValue = ds.Tables[0].Rows[i][0].ToString();
                    fillcounties(state.SelectedItem.ToString());
                    county.SelectedValue = ds.Tables[0].Rows[i][2].ToString();

                    cb_area.SelectedValue = ds.Tables[0].Rows[i][1].ToString();
                    string temp = ds.Tables[0].Rows[i]["sector_id"].ToString();
                    string temp2 = ds.Tables[0].Rows[i]["sector_name"].ToString();
                    cb_sector.SelectedValue = temp;
                }
                cb_city.Items.Clear();


                for (int i = 0; i < ds.Tables[1].Rows.Count; i++)
                {
                    string citys = ds.Tables[1].Rows[i][0].ToString();
                    string cityid = ds.Tables[1].Rows[i][1].ToString();
                    ListItem li = new ListItem(citys, cityid);
                    cb_city.Items.Add(li);
                    
                }
                cb_city.Enabled = true;
                setMonto();


            }
            else
            {
                cb_city.Enabled = false;
                if (cb_city.Items.Count>0)      cb_city.SelectedIndex = 0;
                if (state.Items.Count > 0)      state.SelectedIndex = 0;
                if (cb_area.Items.Count > 0)    cb_area.SelectedIndex = 0;
                if (cb_sector.Items.Count > 0)  cb_sector.SelectedIndex = 0;
                if (county.Items.Count > 0)    county.SelectedIndex = -1;
                if (res == 0)
                {
                    lb_coverage.Visible = true;
                    Response.Write("<script>alert('Sorry this is an uncovered area')</script>");

                }
                else
                {
                    lzip.Visible = true;
                }
            }
        }
        else {
            cb_city.Enabled = false;
            cb_city.SelectedIndex = 0;
            state.SelectedIndex = 0;
            cb_area.SelectedIndex = 0;
            cb_sector.SelectedIndex = 0;
            county.SelectedIndex = -1;
            lzip.Visible = true;
        
        }

    }


    protected void lnk_save_Click(object sender, EventArgs e)
    {
        lnk_save.Enabled = false;
        lzip.Visible = false;
        lerror.Text = "";
        int validarprod = 1;

        string type = DB.getProductType(jobtype.SelectedValue);
        if ((type.ToUpper().Equals("INT") || type.ToUpper().Equals("INTREP")))
        {
            if (ContactInformation.Text.Equals(""))
            {
                validarprod = 0;
                Label5.Text = "Required Field";
            }
            else
            {
                validarprod = 1;
            }
        }

        if (!ordernum.Text.Equals("") && CheckBox1.Checked)
        {

            lerror.Text = "Please Assign an Order # or we will generate one automatically.";
            lerror.Visible = true;
            validarprod = validarprod * 0;
        }

        int companycoverage= 0;
        if (cbcompany.SelectedValue.Equals("1")){companycoverage=1;}
       // uitest.Text = companycoverage.ToString();
        
        //validando que no sea en una ciudad donde las interiores o un producto no tenga cobertura, 0= busca para todos, #= busa para cia en particular
        int coverturaCiudad = DB.coverageCityProduct(cb_city.SelectedValue, int.Parse(jobtype.SelectedValue),companycoverage);

        if (validarCombo() == 1)
        {

            if (P_duedate2.Visible == false) {
                Duedate.Text = DateTime.Today.AddDays(2).ToShortDateString();
              // string[] temp = Duedate.Text.Split('/');
               // Duedate.Text = temp[1] + "/" + temp[0] + "/" + temp[2];
            }

            int respuesta = Utility.ValidateDate(Duedate.Text);
            string horavalidar = Utility.HoraAMPMtoFormato24horas(duetimehour.Text, duetimeampm.Text);
            int resulthora = Utility.ValidarHora(horavalidar);
            int manana= Utility.isTomorrow(Duedate.Text);
            int hoy = 0;
            if (respuesta == 1) { resulthora = 1; }
            else if (respuesta == 2) { 
                
                respuesta = 1;
                hoy = 1;
            }
            

            if (respuesta == 1)
            {

                if (resulthora == 1)
                {
                    if (coverturaCiudad == 1)
                    {
                        if (validarprod == 1 )
                        {

                            copiaropt();
                            setMonto();
                            if (hoy == 1 && ruser != null && ruser.getPerfilId().Equals("1"))
                            {
                                lb_hoy.Text = hoy.ToString();
                                ModalPopupExtender1.Show();
                            }
                            else
                            {
                                if (hoy == 0 && ruser != null && ruser.getPerfilId().Equals("1") && manana == 1 && DateTime.Now.Hour > 19)
                                {
                                    lb_hoy.Text = hoy.ToString();
                                    ModalPopupExtender1.Show();
                                }
                                else
                                {
                                    preguarda(hoy);
                                }
                            }


                        }
                    }
                    else {
                        Response.Write("<script>alert('This service is not provided to the requested area!')</script>");
                    
                    }

                }//fin if time and product
                else
                {// Response.Write("<script> alert('Please enter correct time value ');</script>");
                    lerror.Text = "Please enter correct time value";
                }
            }
            else
            {
                lerror.Text = "Please enter correct date value.";
                /*Response.Write("<" + "script language='javascript'>");
                Response.Write("alert('Please enter correct date value.');");
                Response.Write("<" + "/script>");*/

            }


        }
        else
        {
            lerror.Text = "Please enter a valid date.";
            /*  Response.Write("<" + "script language='javascript'>");
              Response.Write("alert('Please enter a valid date.');");
              Response.Write("<" + "/script>");*/
        }
        lnk_save.Enabled = true;
    }

    protected void preguarda(int hoy) {
        int guardar = guardarbd();
        if (guardar != 0)
        {
            string telephone = "";
            ruser = (rUser)Session["userid"];
            RE_Direccion dir = (RE_Direccion)ruser.direcciones[0];

            telephone += dir.telof;
            telephone += "    " + dir.telcel;



            RE_GenericBean permi = Utility.getPermisobyRuser(ruser, 2);
            long permiso = permi.int64C1;
            long test1 = (permiso & 2);
            long test2 = (permi.int64C1 & 2);
            if ((test1 == 2))
            {
                try
                {
                    string from = "bpo@bpophotos.com";
                    //string to = "neworder@bpophotos.com";

                    string to = "nancysalazar@vickocorp.com;jorgeb@vickocorp.com;victorr@vickocorp.com;victorp@vickocorp.com; ";
                    string subject = "";
                    if (hoy == 1)
                    {
                        subject = "RUSH new order #" + stordernum;
                    }
                    else
                    {
                        subject = "New Order #" + stordernum;
                    }

                    string body = "Hello Team,<br>This is an automated email confirming that a new order has been received.<br> Please assign as soon as possible, and if there are any issues with this order contact " + ruser.getNombre().ToUpper() + " " + ruser.getApellido().ToUpper() + " immediately. ";
                    if (exp.Checked) { body = body + "<br><br><b>Client:</b>" + ruser.getNombre().ToUpper() + " " + ruser.getApellido().ToUpper() + "<br><b>Client Email:</b>" + ruser.getEmail() + "<br><b>Client Contact Phone:</b>" + telephone + "<br><b>Report Type:</b> " + jobtype.SelectedItem.ToString() + "<b>  (Expedite)  Fee:</b>" + amount.Text; }
                    else { body = body + "<br><br><b>Client:</b>" + ruser.getNombre().ToUpper() + " " + ruser.getApellido().ToUpper() + "<br><b>Client Email:</b>" + ruser.getEmail() + "<br><b>Client Contact Phone:</b>" + telephone + "<br><br><b>Report Type:</b> " + jobtype.SelectedItem.ToString() + "<b>    Fee:</b>" + amount.Text; }
                    body = body + "<br><b>Due Date:</b>" + Duedate.Text + " <b>Due Time: </b>" + duetimehour.Text + " " + duetimeampm.Text;
                    body = body + "<br><b>Address:</b>" + stnum.Text.ToUpper() + " " + stadd.Text.ToUpper();
                    body = body + "<br><b>City:</b> " + cb_city.SelectedItem.ToString().ToUpper() + " <b>State: </b>" + state.SelectedItem.ToString() + " <b>Zip Code: </b>" + zip.Text;
                    body = body + "<br><b>Comments:</b>" + comments.Text;
                    body = body + "<br><b>Services Requested:</b>";

                    int produc_id = int.Parse(jobtype.SelectedValue);
                    if (produc_id == 2 || produc_id == 7) { /*to += ";joshv@pacificstarfinancial;alejandroz@pacificstarfinancial.com";*/ }

                    DataSet dsprocess = DB.getProcess(produc_id);
                    int hasta = dsprocess.Tables[0].Rows.Count;

                    for (int i = 0; i <= hasta - 1; i++)
                    {
                        body = body + "<br>" + dsprocess.Tables[0].Rows[i]["name"].ToString().ToUpper();



                    }

                    Utility.sendMail(from, to, subject, body,"");
                    //envio mail si queda sujeto a probacion porque duedate es hoy
                    if (hoy == 1)
                    {
                        string fromhoy = "bpo@bpophotos.com";
                        //string to = "neworder@bpophotos.com";
                        string tohoy = ruser.getEmail();



                        /*  string subjecthoy = " bpophotos.com  Order #" + stordernum;
                          string bodyhoy = "Hello:<br><br>  Due to the requested due date on this order, a special approval confirmation is required from our management team. Even though, we will make every possible attempt to try to complete your request on time, ";
                          bodyhoy += "there might be circumstances where we will need to make adjustments. You should receive an email or a phone call within the next hour to confirm in case there are any issues.";
                          bodyhoy += "<br><br>Please don't hesitate on calling or emailing us with any questions. Phone number after hours   949-422-4764.";
                          bodyhoy += "<br><br>Thank you very much for doing business with us.<br><br>bpophotos.com  team ";


                          */


                        string subjecthoy = " bpophotos.com  Order #" + stordernum;
                        string bodyhoy = "Hello:<br><br>   Due to the requested due date on this order, a special confirmation is required from our management team. Even though, we will make every possible attempt to try to complete your request on time, ";
                        bodyhoy += " there might be circumstances where we will need to make adjustments. You should receive an email or a phone call within the next hour to confirm or to make changes to your order requirements. ";

                        bodyhoy += "<br><br>Thank you very much for doing business with us.<br><br>bpophotos.com  team ";



                        Utility.sendMail(fromhoy, tohoy, subjecthoy, bodyhoy,"");
                    }
                   
                }
                catch (Exception ex)
                {
                    Utility.writeError("Error envio mail orderplacemente " + ex.Message + " -" + ex.StackTrace);
                }
            }
            //Response.Write("<script> alert('Your Order is Set on bpophotos.com ');</script>");
            if (ruser.getPerfilId().Equals("1"))
            {
                Session["paidclient"] = 1;
                DataSet dsuser = DB.GetProductsbyUser(cbclient.SelectedValue);
                if (dsuser != null)
                {
                    for (int j = 0; j <= (dsuser.Tables[0].Rows.Count - 1); j++)
                    {
                        if (jobtype.SelectedValue.Equals(dsuser.Tables[0].Rows[j][0].ToString()))
                        {
                            amount.Text = Utility.formatNumber(dsuser.Tables[0].Rows[j][1].ToString());
                            RE_GenericBean rinfo = new RE_GenericBean();
                            rinfo.strC1 = guardar.ToString();
                            rinfo.strC2 = ordernum.Text;
                            if (ordernum.Text.Equals(""))
                            {
                                rinfo.strC2 = guardar.ToString();
                            }

                            rinfo.strC3 = stnum.Text + " " + stadd.Text;
                            rinfo.strC4 = cb_city.SelectedItem.ToString();

                            // PaypalButt(ruser.getUsuarioId(), dsuser.Tables[0].Rows[j][1].ToString(),rinfo );
                            setMonto();
                            PaypalButt(ruser.getUsuarioId(), monto.ToString(), rinfo);
                        }
                    }

                }
                if ((PNOrd & 2097152) == 2097152)
                    p_hide_ModalPopupExtender.Show();
            }
            else
            {
                Response.Redirect("WorkSpace.aspx");
            }


        }
        else
        {
            // Response.Write("<script> alert('Fail on add new order!!');</script>");


        }
    
    
    
    }
    protected void lnk_saveadd_Click(object sender, EventArgs e)
    {
        lnk_saveadd.Enabled = false;
        lerror.Text = "";
        lzip.Visible = false;
        int validarprod = 1;

        string type = DB.getProductType(jobtype.SelectedValue);
        if ((type.ToUpper().Equals("INT") || type.ToUpper().Equals("INTREP")))
        {
            if (ContactInformation.Text.Equals(""))
            {
                validarprod = 0;
                Label5.Text = "Required Field";
            }
            else
            {
                validarprod = 1;
            }
        }

        if (!ordernum.Text.Equals("") && CheckBox1.Checked)
        {

            lerror.Text = "Please Assign an Order # or we will generate one automatically.";
            lerror.Visible = true;
            validarprod = validarprod * 0;
        }
        int companycoverage = 0;
        if (cbcompany.SelectedValue.Equals("1")) { companycoverage = 1; }
       // uitest.Text = companycoverage.ToString();
        int coverturaCiudad = DB.coverageCityProduct(cb_city.SelectedValue, int.Parse(jobtype.SelectedValue), companycoverage);
        if (validarCombo() == 1)
        {

            if (P_duedate2.Visible == false)
            {
                Duedate.Text = DateTime.Today.AddDays(2).ToShortDateString();
               // string[] temp = Duedate.Text.Split('/');
               // Duedate.Text = temp[1] + "/" + temp[0] + "/" + temp[2];
            }
            int respuesta = Utility.ValidateDate(Duedate.Text);
            string horavalidar = Utility.HoraAMPMtoFormato24horas(duetimehour.Text, duetimeampm.Text);
            int resulthora = Utility.ValidarHora(horavalidar);

            if (respuesta == 1) { resulthora = 1; }
            else if (respuesta == 2) { respuesta = 1; }
            else { }

            if (respuesta == 1)
            {

                if (resulthora == 1)
                {
                    if (coverturaCiudad == 1)
                    {
                        if (validarprod == 1)
                        {

                            copiaropt();
                            if (guardarbd() != 0)
                            {
                                ruser = (rUser)Session["userid"];
                                RE_GenericBean permi = Utility.getPermisobyRuser(ruser, 2);
                                long permiso = permi.int64C1;
                                if (((permiso & 2) == 2) || ((permiso) & 2) == 2)
                                    if (true)
                                    {
                                        try
                                        {
                                            string from = "bpo@bpophotos.com";
                                            string to = "neworder@bpophotos.com";
                                            string subject = "New Order #" + stordernum;
                                            string body = "Hello Team,<br>This is an automated email confirming that a new order has been received.<br> Please assign as soon as possible, and if there are any issues with this order contact " + ruser.getNombre().ToUpper() + " " + ruser.getApellido().ToUpper() + " immediately. ";
                                            if (exp.Checked) { body = body + "<br><br><b>Report Type:</b> " + jobtype.Text + "<b>  (Expedite)  Fee:</b>" + amount.Text; }
                                            else { body = body + "<br><br><b>Report Type:</b> " + jobtype.Text + "<b>    Fee:</b>" + amount.Text; }
                                            body = body + "<br><b>Due Date:</b>" + Duedate.Text + " <b>Due Time: </b>" + duetimehour.Text + " " + duetimeampm.Text;
                                            body = body + "<br><b>Address:</b>" + stnum.Text.ToUpper() + " " + stadd.Text.ToUpper();
                                            body = body + "<br><b>City:</b> " + cb_city.SelectedItem.ToString().ToUpper() + " <b>State: </b>" + state.SelectedValue.ToUpper() + " <b>Zip Code: </b>" + zip.Text;
                                            body = body + "<br><b>Comments:</b>" + comments.Text;
                                            body = body + "<br><b>Services Requested:</b>";
                                            body = body + "<br>";
                                            int produc_id = int.Parse(jobtype.SelectedValue);
                                            DataSet dsprocess = DB.getProcess(produc_id);
                                            int hasta = dsprocess.Tables[0].Rows.Count;

                                            for (int i = 0; i <= hasta - 1; i++)
                                            {
                                                body = body + "<br>" + dsprocess.Tables[0].Rows[i]["name"].ToString().ToUpper();



                                            }

                                            Utility.sendMail(from, to, subject, body,"");
                                        }
                                        catch (Exception ex)
                                        {
                                            Utility.writeError("Error envio mail orderplacemente " + ex.Message + " -" + ex.StackTrace);
                                        }
                                    }
                                //Response.Write("<script> alert('Your Order is Set on bpophotos.com ');</script>");
                                if (ruser.getPerfilId().Equals("1"))
                                {
                                    Session["paidclient"] = 2;
                                    if ((PNOrd & 2097152) == 2097152)
                                        p_hide_ModalPopupExtender.Show();
                                }
                                else
                                {
                                    Response.Redirect("OrderPlacement.aspx");
                                }



                            }
                            else
                            {
                                // Response.Write("<script> alert('Fail on add new order!!');</script>");


                            }

                        }
                    }
                    else
                    {
                        Response.Write("<script>alert('This service is not provided to the requested area!')</script>");

                    }

                }//fin if time and product
                else
                {// Response.Write("<script> alert('Please enter correct time value ');</script>");
                    lerror.Text = "Please enter correct time value";
                }
            }
            else
            {
                lerror.Text = "Please enter correct date value.";
                /*Response.Write("<" + "script language='javascript'>");
                Response.Write("alert('Please enter correct date value.');");
                Response.Write("<" + "/script>");*/

            }


        }
        else
        {
            lerror.Text = "Please enter a valid date.";
            /*  Response.Write("<" + "script language='javascript'>");
              Response.Write("alert('Please enter a valid date.');");
              Response.Write("<" + "/script>");*/
        }
        lnk_saveadd.Enabled = true;
    }
    
    private DataSet cargaraccounts()
    {
        DataSet result;
        com.bpophotos.www.Service service = new com.bpophotos.www.Service();

        try
        {


            string xmlaccount = service.getAccounts();
            result = Utility.getAccounts(xmlaccount);

        }
        catch (Exception ex)
        {
            Utility.writeError(ex.Message + ex.StackTrace);
            result= null;
        }
        return result;
    }
    protected void cbclient_SelectedIndexChanged(object sender, EventArgs e)
    {
        rUser ruser = (rUser)Session["userid"];
        if (cbclient.SelectedValue.Equals("PACIFICSTAR") && !ruser.getPerfilId().ToUpper().Equals("CLIENT"))
        {
            PpsfPrice.Visible = true;
        }
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {

    }
    protected void lnk_cancelpaid_Click(object sender, EventArgs e)
    {
        p_hide_ModalPopupExtender.Hide();
        if (Session["paidclient"] != null)
        {
            int paidclient = (int)Session["paidclient"];

            if (paidclient == 1)
            {
                Session["paidclient"] = null;
                p_hide_ModalPopupExtender.Hide();
                Response.Redirect("WorkSpace.aspx");

            }
            if (paidclient == 2)
            {
                Session["paidclient"] = null;
                p_hide_ModalPopupExtender.Hide();
                Response.Redirect("OrderPlacement.aspx");

            }
        }


    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        
        preguarda(int.Parse(lb_hoy.Text));
    }
}
F